package com.tai.java8;

import org.junit.Test;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * The type Collection demo.
 *
 * @description: java8集合测试
 * @author: Taylor
 * @date :  2021-03-01 10:49
 */
public class CollectionDemo {

    private static List<Student> studentList = new ArrayList<>();

    static {
        studentList.add(new Student(1L,"Taylor",30));
        studentList.add(new Student(2L,"Lily",26));
        studentList.add(new Student(3L,"Tom",20));
        studentList.add(new Student(4L,"Jack",34));
        studentList.add(new Student(5L,"Andy",38));
        studentList.add(new Student(6L,"Tony",24));
        studentList.add(new Student(7L,"Jim",33));
        studentList.add(new Student(8L,"Lucy",35));
        studentList.add(new Student(9L,"Kobe",39));
    }

    /**
     * map 测试
     */
    @Test
    public void testMap(){
        List<String> stringList = studentList.stream().map(Student::getStudentName).collect(Collectors.toList());
        stringList.forEach(s-> System.out.println(s));
        System.out.println("-------");
        //获取大于35岁的人的名字
        List<String> stringList1 = studentList.stream()
                .filter(student -> student.getAge() > 35)
                .map(student -> student.getStudentName()).collect(Collectors.toList());
        stringList1.forEach(s -> System.out.println(s));
    }

    /**
     * filter 测试
     */
    @Test
    public void testFilter(){
        // 过滤出年龄大于30的数据
        List<Student> studentList0 = CollectionDemo.studentList.stream()
                .filter(student -> student.getAge() > 30).collect(Collectors.toList());
        studentList0.forEach(student -> System.out.println(student));
        System.out.println("-------------");
        // filter 链式调用实现 and
        List<Student> studentList1 = studentList.stream()
                .filter(student -> student.getAge() > 30)
                .filter(student -> student.getStudentName().startsWith("J"))
                .collect(Collectors.toList());
        studentList1.forEach(student -> System.out.println(student));
        System.out.println("==========");
        // 通过 Predicate 实现 or
        Predicate<Student> p1 = x->x.getAge()>30;
        Predicate<Student> p2 = x->x.getStudentName().startsWith("T");

        List<Student> studentList2 = studentList.stream().filter(p1.or(p2)).collect(Collectors.toList());
        studentList2.forEach(student -> System.out.println(student));
    }
}
